home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 4354 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  49 lines

  1. Newsgroups: comp.lang.c
  2. Path: mxsld2.pd.infn.it!LORETI
  3. From: loreti@mxsld2.pd.infn.it (Maurizio Loreti)
  4. Subject: Re: Checking to See if a File Exists
  5. X-Nntp-Posting-Host: mxsld2.pd.infn.it
  6. Message-ID: <DM81w4.CB6@news.cern.ch>
  7. Sender: news@news.cern.ch (USENET News System)
  8. Reply-To: loreti@mxsld2.pd.infn.it
  9. Organization: I.N.F.N. Padova - CDF/CMS VAXcluster
  10. References: <DLtI7G.HpE@midway.uchicago.edu>
  11. Date: Sat, 3 Feb 1996 22:45:36 GMT
  12.  
  13. In article <DLtI7G.HpE@midway.uchicago.edu>, jaj3@kimbark.uchicago.edu (josef jurek) writes:
  14. >
  15. >How does one check from a C program to see whether a file
  16. >exists or not?
  17.  
  18. Apparently, while you read the FAQ list before posting, you missed Q/A
  19. 19.11.
  20.  
  21. 19.11:    How can I check whether a file exists?  I want to warn the user
  22.     if a requested input file is missing.
  23.  
  24. A:    It's surprisingly difficult to make this determination reliably
  25.     and portably.  Any test you make can be invalidated if the file
  26.     is created or deleted (i.e. by some other process) between the
  27.     time you make the test and the time you try to open the file.
  28.  
  29.     Three possible test routines are stat(), access(), and fopen().
  30.     (To make an approximate test for file existence with fopen(),
  31.     just open for reading and close immediately.)  Of these, only
  32.     fopen() is widely portable, and access(), where it exists, must
  33.     be used carefully if the program uses the Unix set-UID feature.
  34.  
  35.     Rather than trying to predict in advance whether an operation
  36.     such as opening a file will succeed, it's often better to try
  37.     it, check the return value, and complain if it fails.
  38.     (Obviously, this approach won't work if you're trying to avoid
  39.     overwriting an existing file, unless you've got something like
  40.     the O_EXCL file opening option available, which does just what
  41.     you want in this case.)
  42.  
  43.     References: PCS Sec. 12 pp. 189,213; POSIX Sec. 5.3.1,
  44.     Sec. 5.6.2, Sec. 5.6.3.
  45.  
  46. --
  47. Maurizio Loreti                       http://mvxpd5.pd.infn.it/wwwcdf/mlo.html
  48. Un. of Padova, Dept. of Physics - Padova, Italy          loreti@padova.infn.it
  49.